<script setup lang="ts">
import { AuForm } from "@/components/AuForm";
import { getCurrentInstance, h, nextTick, reactive, ref } from "vue";
import { VxeGridInstance, VxeGridProps, VxeUI } from "vxe-table";
import {
  Datum,
  formulaVerGetList,
  updateStatus,
  versionsAdd,
  versionsDelete,
  versionsUpdate
} from "@/api/teaInfuser/formula";
import { pick } from "lodash-unified";
import IssueModal from "@/components/Autata/IssueModal.vue";
import { useDetail } from "../hooks";
import { AuModal } from "@/components/AuModal";
import { ElMessage, ElMessageBox } from "element-plus";
import { AuTable } from "@/components/AuTable";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import { addVersions, getVersionReleaseList } from "@/api/teaInfuser/formula";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

defineOptions({
  name: "FormulaVersion"
});

const { proxy } = getCurrentInstance();
const { toDetail } = useDetail();
const formList = ref([
  {
    type: "input",
    key: "name",
    label: "formula.version.name",
    placeholder: "formula.version.name_placeholder"
  }
  // {
  //   type: "select",
  //   key: "publish_status",
  //   label: "formula.version.status",
  //   placeholder: "formula.version.status_placeholder",
  //   labelKey: "label",
  //   valueKey: "value",
  //   emptyValues: [null, undefined],
  //   options: [
  //     {
  //       value: "",
  //       label: "formula.version.status_all"
  //     },
  //     {
  //       value: "0",
  //       label: "formula.version.status_down"
  //     },
  //     {
  //       value: "1",
  //       label: "formula.version.status_up"
  //     }
  //   ],
  //   defaultValue: ""
  // }
]);
const formPopList = ref([
  {
    type: "input",
    key: "name",
    label: "formula.version.name",
    placeholder: "formula.version.name_placeholder",
    required: true
  },
  {
    type: "select",
    key: "copy_version",
    label: "formula.version.copy",
    placeholder: "formula.version.copy_placeholder",
    labelKey: "name",
    valueKey: "id",
    columns: []
  },
  {
    type: "input",
    key: "furnace_temp",
    label: "formula.version.furnace_temp",
    placeholder: "formula.version.furnace_temp_placeholder",
    formatter: (value: string) => value.replace(/[^0-9]/g, ""),
    parser: (value: string) => value.replace(/[^0-9]/g, ""),
    suffixIcon: h("span", {}, "℃")
  },
  {
    type: "input",
    key: "note",
    label: "table.note",
    placeholder: "formula.version.note_placeholder",
    inType: "textarea"
  }
]);
const activeType = ref(null);
const showPopup = ref(false);

const showTreePopup = ref(false);
const versionId = ref(0);

// region 组件 ref 部分
const xGrid = ref();
const formRef = ref();
const formPopRef = ref();
// endregion

const gridOptions = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  columns: [
    { field: "name", title: "formula.version.name", align: "center" },
    { field: "note", title: "table.note", align: "center" },
    {
      field: "device_type",
      title: "formula.version.device_type",
      align: "center"
    },
    {
      field: "furnace_temp",
      title: "formula.version.furnace_temp",
      align: "center"
    },
    // {
    //   field: "publish_status",
    //   title: "formula.version.status",
    //   slots: { default: "status_default" },
    //   align: "center"
    // },
    {
      field: "update_time",
      title: "formulaVersion.updateTime",
      align: "center",
      width: 190
    }
  ],
  actions: [ACTION_TYPE.TADD, ACTION_TYPE.TDELETE, ACTION_TYPE.EDIT],
  operateTools: [
    {
      key: ACTION_TYPE.VIEW,
      name: "formula.version.view_formula"
    },
    // {
    //   key: ACTION_TYPE.PUTAWAY,
    //   name: "formula.version.status_down",
    //   hiddenHandle: (row: ObjectProps) => {
    //     return row.publish_status === 0;
    //   }
    // },
    // {
    //   key: ACTION_TYPE.OFFSHELVE,
    //   name: "formula.version.status_up",
    //   hiddenHandle: (row: ObjectProps) => {
    //     return row.publish_status === 1;
    //   }
    // },
    {
      key: ACTION_TYPE.ISSUED,
      name: "formula.version.issue_formula"
    }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (params: ObjectProps) => {
        return formulaVerGetList(params);
      },
      param: () => formRef.value.getFormData()
    }
  }
});

// region 公共引用方法部分
/**
 * 获取列表
 * @param currentPage
 * @param pageSize
 */
const findList = (
  currentPage: number,
  pageSize: number
): Promise<{
  page: {
    total: number;
  };
  result: Datum[];
}> => {
  return new Promise(resolve => {
    const params = {
      start_page: currentPage,
      size: pageSize,
      ...formRef.value.getFormData()
    };
    formulaVerGetList(params)
      .then(res => {
        console.log(res);
        resolve({
          page: {
            total: res.pageCount
          },
          result: res.data
        });
      })
      .catch(err => {
        resolve({
          page: {
            total: 0
          },
          result: []
        });
      });
  });
};

const getPopVersion = () => {
  const params = {
    start_page: 1,
    size: 0
  };
  formulaVerGetList(params).then(res => {
    // formPopList.value[2].options = res.data;
    formPopRef.value.setFormProps("copy_version", {
      options: res.data,
      hidden: false
    });
  });
};

/**
 * 上架/下架
 * @param row {Datum}
 */
const handleUpOrDown = (row: Datum) => {
  const status =
    row.publish_status === 0
      ? t("formula.version.status_up")
      : t("formula.version.status_down");
  const msg = t("formula.version.status_change_confirm", {
    status,
    name: row.name
  });

  proxy.$auMessageBox.confirm(msg, t("notice.title")).then(() => {
    const param = {
      publish_status: row.publish_status ? 0 : 1,
      formulaList: JSON.stringify([{ id: row.id }])
    };
    updateStatus(param).then(res => {
      if (res.code === 200) {
        VxeUI.modal.message({
          content: t("notice.operation_success"),
          status: "success"
        });
        search();
      }
    });
  });
};

// endregion

// region 组件的事件部分
const search = () => {
  xGrid.value.refresh();
};

const actionClick = ({ key, row }) => {
  activeType.value = key;
  switch (key) {
    case ACTION_TYPE.TADD:
      showPopup.value = true;
      getPopVersion();
      nextTick(() => {
        formPopRef.value.reset();
      });
      break;
    case ACTION_TYPE.EDIT:
      showPopup.value = true;
      nextTick(() => {
        formPopRef.value.setFormData(row);
        formPopRef.value.setFormProps("copy_version", { hidden: true });
      });
      break;
    case ACTION_TYPE.TDELETE:
      proxy.$auMessageBox
        .confirm(t("formula.version.delete_confirm"), t("notice.title"), {
          type: "error"
        })
        .then(() => {
          const checkRows = xGrid.value.getCheckboxRecords();
          if (checkRows.length > 0) {
            const ids = checkRows.map(item => ({ id: item.id }));
            versionsDelete({ delList: JSON.stringify(ids) }).then(res => {
              if (res.code === 200) {
                VxeUI.modal.message({
                  content: t("notice.operation_success"),
                  status: "success"
                });
                xGrid.value.refresh();
              }
            });
          }
        })
        .catch(() => {});
      break;
    case ACTION_TYPE.OFFSHELVE:
    case ACTION_TYPE.PUTAWAY:
      handleUpOrDown(row);
      break;
    case ACTION_TYPE.ISSUED:
      versionId.value = row.id;
      showTreePopup.value = true;
      break;
    case ACTION_TYPE.VIEW:
      // showFormulaViewModal.value = true;
      toDetail(pick(row, ["id", "name"]) as {}, "query");
      break;
    default:
      break;
  }
};

const handleConfirm = async () => {
  const validate = await formPopRef.value.validate();
  if (!validate.check) return;
  let formData = formPopRef.value.getFormData();
  let api = versionsAdd;
  if (activeType.value === "add") {
    api = versionsAdd;
  } else if (activeType.value === "edit") {
    api = versionsUpdate;
    formData = pick(formData, ["id", "name", "furnace_temp", "note"]);
  }
  api(formData).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: formData.id
          ? t("formula.version.edit_success")
          : t("formula.version.add_success"),
        type: "success"
      });
      showPopup.value = false;
      xGrid.value.refresh();
    }
  });
};

const handleTreeConfirm = () => {};

// endregion
</script>
<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm
        ref="formRef"
        labelWidth="60px"
        :formList="formList"
        @submit="search"
      />
    </vxe-card>

    <vxe-card
      :padding="false"
      class="mt-[16px] flex-grow overflow-hidden table-wrap"
      :border="false"
    >
      <!--      <vxe-grid ref="xGrid" v-bind="gridOptions" class="h-full">-->
      <!--        <template #toolbar_tools>-->
      <!--          <el-button-->
      <!--            type="primary"-->
      <!--            class="my-[0.5em]"-->
      <!--            @click="actionClick('add', null)"-->
      <!--            >新增-->
      <!--          </el-button>-->
      <!--          <el-button-->
      <!--            type="danger"-->
      <!--            plain-->
      <!--            :disabled="xGrid?.getCheckboxRecords().length === 0"-->
      <!--            @click="actionClick('delete', null)"-->
      <!--            >删除-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--        <template #status="{ row }">-->
      <!--          <el-tag :type="row.publish_status ? 'primary' : 'danger'"-->
      <!--            >{{ row.publish_status ? "上架" : "下架" }}-->
      <!--          </el-tag>-->
      <!--        </template>-->
      <!--        <template #operate="{ row }">-->
      <!--          <el-link-->
      <!--            type="primary"-->
      <!--            :underline="false"-->
      <!--            @click="actionClick('edit', row)"-->
      <!--          >-->
      <!--            编辑-->
      <!--          </el-link>-->
      <!--          <el-divider direction="vertical" />-->
      <!--          <el-link-->
      <!--            type="primary"-->
      <!--            :underline="false"-->
      <!--            @click="actionClick('view', row)"-->
      <!--          >-->
      <!--            查看配方-->
      <!--          </el-link>-->
      <!--          <el-divider direction="vertical" />-->
      <!--          <el-link-->
      <!--            v-if="!row.publish_status"-->
      <!--            type="primary"-->
      <!--            :underline="false"-->
      <!--            @click="actionClick('putaway', row)"-->
      <!--          >-->
      <!--            上架-->
      <!--          </el-link>-->
      <!--          <el-divider v-if="!row.publish_status" direction="vertical" />-->
      <!--          <el-link-->
      <!--            v-if="row.publish_status"-->
      <!--            type="primary"-->
      <!--            :underline="false"-->
      <!--            @click="actionClick('delist', row)"-->
      <!--          >-->
      <!--            下架-->
      <!--          </el-link>-->
      <!--          <el-divider v-if="row.publish_status" direction="vertical" />-->
      <!--          <el-link-->
      <!--            type="primary"-->
      <!--            :underline="false"-->
      <!--            @click="actionClick('issue', row)"-->
      <!--          >-->
      <!--            下发配方-->
      <!--          </el-link>-->
      <!--        </template>-->
      <!--      </vxe-grid>-->
      <AuTable ref="xGrid" v-bind="gridOptions" @actionClick="actionClick">
        <template #status_default="{ row }">
          <el-tag :type="row.publish_status ? 'success' : 'info'"
            >{{
              row.publish_status
                ? t("formula.version.status_up")
                : t("formula.version.status_down")
            }}
          </el-tag>
        </template>
      </AuTable>
    </vxe-card>

    <AuModal
      v-model="showPopup"
      :title="
        activeType === ACTION_TYPE.TADD
          ? t('formula.version.add_title')
          : t('formula.version.edit_title')
      "
      :width="460"
      show-zoom
      :padding="false"
      @handleConfirm="handleConfirm"
    >
      <div class="flex justify-center pt-[30px] pb-[12px] pr-[20px]">
        <AuForm
          ref="formPopRef"
          :formList="formPopList"
          :isInline="false"
          :hiddenBtn="true"
          class="!w-[400px]"
        />
      </div>
    </AuModal>

    <!--    <IssueModal v-model:showModal="showTreePopup" :versionId="versionId" />-->
    <IssueModal
      v-model="showTreePopup"
      :versionId="versionId"
      device-id-type="ATT-S"
      :isJsonString="true"
      :isOnlyShowStore="true"
      :release-fn="[addVersions, getVersionReleaseList]"
    />
    <!--    <FormulaViewModal-->
    <!--      v-model:showModal="showFormulaViewModal"-->
    <!--      :versionId="versionId"-->
    <!--    />-->
  </div>
</template>
